﻿using CRM.Models;
using System.Linq;
using CRM.Extensions;
using System.Threading.Tasks;
using System.Collections.Generic;
using CRM.ViewModels.User;
using Z.EntityFramework.Plus;

namespace CRM.Services
{
    public  class CompanyService : BaseService
    {
          /// <summary>
        /// 获取公司详情
        /// </summary>
        /// <param name="id"></param>
        /// <returns></returns>
        public Company GetInfo(int id)
        {
            return DbContext.Company.Where(m => m.Id == id).FirstOrDefault();
        }


        /// <summary>
        /// 初始化公司信息
        /// </summary>
        /// <param name="RequestData"></param>
        /// <param name="CurrentCompany"></param>
        /// <param name="ValidityId"></param>
        /// <param name="validity"></param>
        /// <returns></returns>
        public async Task<int> InitCompanyConfig(CompanySubAdd RequestData, Company CurrentCompany,int ValidityId,long validity)
        {
            string ValidityIds = CurrentCompany.ValidityIds + "," + ValidityId;
            Company CompanyModel = new()
            {
                ParentCompanyId = CurrentCompany.Id,
                Name = string.IsNullOrEmpty(RequestData.CompanyName) ? RequestData.TrueName : RequestData.CompanyName,
                RuleId = RequestData.RuleId,
                IsOpenUser = RequestData.IsOpenUser,
                OpenUserNum = RequestData.OpenUserNum,
                IsUnlimitedPoints = RequestData.IsUnlimitedPoints,
                NumberOfPoints = RequestData.NumberOfPoints,
                State = RequestData.State,
                ValidityIds = ValidityIds.Trim(','),
                ShowValidityId = ValidityId,
                ShowValidity = validity,
                CreatIp = HttpContext.GetIPv4(),
                OemId = RequestData.OemId,
                ShowOemId = RequestData.OemId
            };
            await DbContext.Company.AddAsync(CompanyModel);
            await DbContext.SaveChangesAsync();

            return CompanyModel.Id;
        }


        /// <summary>
        /// 更新指定公司信息
        /// </summary>
        /// <param name="dic"></param>
        /// <param name="Id"></param>
        /// <returns></returns>
        public int UpdateComapny(Dictionary<string, object> dic, int Id) {
            return DbContext.Company.Where(m => m.Id == Id).Update(dic);
        }

    }
}
